<template>
  <div class="drawingBoard">
    <div class="box">
      <span>画笔：</span>
      <select v-model="hbSelected">
        <option v-for="(item, index) in hbOptions" :key="index" :value="item.value">{{item.text}}</option>
      </select>
      <select v-model="myColor">
        <option v-for="(item, index) in colorOptions" :key="index" :value="item.value">{{item.text}}</option>
      </select>
      <span>橡皮擦：</span><button @click="clearDraw">清空画布</button>  <button @click="getpic">保存签名</button>
    </div>
    <canvas id="myCanvas" width="375" height="150" @touchstart="draw" ref="imgBox">您的浏览器不支持Canvas</canvas>
    <br>
    <span>签名图片：</span>
    <img :src="pic" class="qianming" >
  </div>
</template>
<script>
export default {
  name: 'drawingBoard',
  data () {
    return {
      hbSelected: '',
      myColor: '',
      hbOptions: [
        { text: '请选择画笔粗细', value: '' },
        { text: '1', value: '1' },
        { text: '5', value: '5' },
        { text: '10', value: '10' },
        { text: '30', value: '30' }
      ],
      colorOptions: [
        { text: '请选择画笔颜色', value: '' },
        { text: '黑色', value: '#000' },
        { text: '白色', value: '#fff' },
        { text: '红色', value: 'red' },
        { text: '粉红色', value: 'pink' },
        { text: '黄色', value: 'yellow' }
      ],
      x: '',
      y: '',
      x2: '',
      y2: '',
      ctx: '',
      offsetLeft: 0,
      offsetTop: 0,
      pic: ''

    }
  },
  created () {
  },
  mounted () {
    var canvas = document.getElementById('myCanvas')
    this.ctx = canvas.getContext('2d')
    this.offsetLeft = canvas.offsetLeft
    this.offsetTop = canvas.offsetTop
  },
  methods: {
    draw (s) {
      var event = s.touches[0]
      this.x = event.clientX - this.offsetLeft
      this.y = event.clientY - this.offsetTop
      this.ctx.beginPath()
      this.ctx.moveTo(this.x, this.y)
      this.ctx.lineWidth = this.hbSelected
      this.ctx.strokeStyle = this.myColor
      document.ontouchmove = (s) => {
        var event = s.touches[0]
        this.x2 = event.clientX - this.offsetLeft
        this.y2 = event.clientY - this.offsetTop
        this.ctx.lineTo(this.x2, this.y2)
        this.ctx.stroke()
      }
      document.ontouchend = () => {
        document.ontouchmove = ''
      }
    },
    getpic () {
      this.$html2canvas(this.$refs.imgBox, {
        scale: 1
      }).then((canvas) => {
        this.pic = canvas.toDataURL('image/jpeg', 1)
      })
    },
    clearDraw () {
      window.reloadPage()
    }
  }
}
</script>
<style lang="less" scoped>
.drawingBoard{
  width: 100%;
  overflow: hidden;
}
canvas{
  background: pink;
}
.qianming{
  display: block;
}
.box{
  margin-bottom: 10px;
}
</style>
